package com.js.aop;

import com.js.pojo.User;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * author:JiangSong
 **/

@Aspect
@Component
public class LogAspect {
    private static final String prePath="F:\\codingDemo\\JavaEE\\newsPublish\\newsPublish\\src\\main\\java\\com\\js\\aop\\";
    @Pointcut("@annotation(com.js.aop.Logger)")
   // @Pointcut("execution(* com.js.controller.AdminController.*(*))")
    public void pointcut(){
        System.out.println("*******it is pointcut");
    }


    @After("pointcut()")
    public void afterSave(JoinPoint point){
        System.out.println("****************after advice---saving Logger************************");
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String beginTime= sdf.format(new Date());
        //得到方法信息
        MethodSignature methodSignature=(MethodSignature) point.getSignature();
        Method method=methodSignature.getMethod();
        Logger logger=method.getAnnotation(Logger.class);
        String option=logger.opt();
        System.out.println("****saving *****");
        save(beginTime, option);
        System.out.println("save finished");
    }



//    @Around("pointcut()")
//    public Object around(ProceedingJoinPoint point)  {
//        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String beginTime= sdf.format(new Date());
//        //得到方法信息
//        MethodSignature methodSignature=(MethodSignature) point.getSignature();
//        Method method=methodSignature.getMethod();
//        Logger logger=method.getAnnotation(Logger.class);
//        String option=logger.opt();
//
//        save(beginTime,option);
//        try {
//            //执行目标方法
//            point.proceed();
//        } catch (Throwable e) {
//            e.printStackTrace();
//            throw new RuntimeException(e);
//        }
//        return null;
//    }

    public void save(String time,String option) {
        System.out.println("into save(),executing");
        //得到请求属性
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //得到前端请求，获得众多参数
        HttpServletRequest request = attributes.getRequest();
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("admin");
        String userName=user.getUsername();


        String log = "用户【"+userName+"】在：【" + time + "】执行" + "【" + option + "】操作！";
        //System.out.println(log);
        try{
            File file = new File(prePath+"logInfo.txt");
            System.out.println("file:"+file.getName()+",location:"+file.getAbsolutePath());
            FileOutputStream fos = null;
            if(!file.exists()){
                System.out.println("no----file not exists,create");
                file.createNewFile();//如果文件不存在，就创建该文件
                fos = new FileOutputStream(file);//首次写入获取
            }else{
                System.out.println("yes---file exists,append");
                //如果文件已存在，那么就在文件末尾追加写入
                fos = new FileOutputStream(file,true);//这里构造方法多了一个参数true,表示在文件末尾追加写入
            }

            OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");//指定以UTF-8格式写入文件

            System.out.println("writing log......");
                //每写入一个日志就换一行
                osw.write(log+"\r\n");

            //写入完成关闭流
            osw.close();
            System.out.println("writing finished....");
        }catch (Exception e) {
            e.printStackTrace();
        }
    }





}
